package com.jt.provider.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.jt.provider.service.ResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.atomic.AtomicLong;

@RestController
@RequestMapping("/provider")
public class ProviderSentinelController {

    //http://ip:port/provider/sentinel01
    @GetMapping("/sentinel01")
    public String doSentinel01(){
        return "sentinel test 01";
    }

    @GetMapping("/sentinel02")
    public String doSentinel02(){
        return "sentinel 02 test  ...";
    }
    @Autowired
    private ResourceService resourceService;
    @GetMapping("/sentinel03")
     public String doGetSource03(){
         resourceService.doGetResource();
         return "sentinel 03 test";
     }

    @GetMapping("/sentinel04")
    public String doSentinel04(){
        resourceService.doGetResource();
        return "sentinel 04 test";
    }

    /**
     * 演示降级(熔断)操作,通过如下代码创造降级的条件
     * 1)服务响应速度慢一些
     * 2)服务不稳定,经常出现异常
     */
    private AtomicLong atomicLong = new AtomicLong(1);
    @GetMapping("/sentinel05")
    public String doSentinel05() throws InterruptedException{
    Long count = atomicLong.getAndIncrement();
    if (count%2==0){
        Thread.sleep(200);//耗时模拟(让线程休眠)
        //throw new RuntimeException();
    }
    return "sentinel is test05";
    }
    @GetMapping("/sentinel06")
    //@SentinelResource("resource")
    public String doSentinel06(@RequestParam("id") Integer id){
        return resourceService.doGetResource(id);
        //return "Get Resource By" + id;
    }
}
